import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from 'views/Home'
import { isLogin } from '../utils/index'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    meta: {
      needLogin: false,
      keepAlive: true
    },
    component: Home
  },
  {
    path: '/cate',
    name: 'cate',
    meta: {
      needLogin: false,
      keepAlive: true
    },
    component: () => import('views/Cate')
  },
  {
    path: '/cart',
    name: 'cart',
    meta: {
      needLogin: true
    },
    component: () => import('views/Cart')
  },
  {
    path: '/user',
    name: 'user',
    meta: {
      needLogin: true
    },
    component: () => import('views/User')
  },
  {
    path: '/detail',
    name: 'detail',
    meta: {
      needLogin: false
    },
    component: () => import('views/Detail')
  },
  {
    path: '/itemList/:cateId',
    name: 'itemList',
    meta: {
      needLogin: false
    },
    component: () => import('views/ItemList')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      needLogin: false
    },
    component: () => import('views/Login')
  },
  {
    path: '/register',
    name: 'register',
    meta: {
      needLogin: false
    },
    component: () => import('views/Register')
  },
  {
    path: '/contactAdd',
    name: 'contactAdd',
    meta: {
      needLogin: true
    },
    component: () => import('views/ContactAdd')
  },
  {
    path: '/contactEdit',
    name: 'contactEdit',
    meta: {
      needLogin: true
    },
    component: () => import('views/ContactEdit')
  },
  {
    path: '/contactLists',
    name: 'contactLists',
    meta: {
      needLogin: true
    },
    component: () => import('views/ContactLists')
  },
  {
    path: '/comfirmOrder',
    name: 'comfirmOrder',
    meta: {
      needLogin: true
    },
    component: () => import('views/ComfirmOrder')
  },
  {
    path: '/search',
    name: 'search',
    meta: {
      needLogin: false
    },
    component: () => import('views/Search')
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    meta: {
      needLogin: false
    },
    component: () => import('views/SearchResult')
  }
]

const router = new VueRouter({
  routes
})

// 登录鉴权
router.beforeEach((to, from, next) => {
  // 当前路由是否需要登录
  if (!to.meta.needLogin) {
    // 不需要登录
    next()
  } else {
    // 需要登录
    if (isLogin()) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  }
})

export default router
